import Variable from "./variable.js"

const {
	BaseUrl
} = Variable;


export const request = async obj => {
	return new Promise(async (resolve, reject) => {
		let {
			url,
			data,
			method,
			header
		} = obj;
		if (!url) return;
		url = BaseUrl + url; // 请求地址

		let systemInfoRes = uni.getSystemInfoSync();
		console.log('systemInfo', systemInfoRes);


		let commonParamObj = {};
		let p = 1;


		// 处理h5的公共参数，比较少
		// #ifdef H5
		p = 1;
		// #endif

		// 处理微信小程序的公共参数
		// #ifdef MP-WEIXIN
		p = 2;
		// #endif

		// #ifdef MP-ALIPAY
		p = 2;
		// #endif

		// #ifdef MP-QQ
		p = 2;
		// #endif

		// #ifdef APP-IOS
		p = 2;
		// #endif

		// #ifdef APP-ANDROID	
		p = 2;
		// #endif

		commonParamObj = Object.assign(systemInfoRes, {
			"p": p
		});

		let commonParamJson = JSON.stringify(commonParamObj);
		let dataObj = Object.assign(data, {
			_commonParam: commonParamJson
		});
		method = method || "POST"; // 请求方法

		let jwtToken = uni.getStorageSync('jwtToken');
		header = header || {
			'Content-type': 'application/x-www-form-urlencoded',
			'Authorization': jwtToken,
		}; // 请求header信息


		// 请求返回信息
		const [error, res] = await uni.request({
			url,
			data: dataObj,
			method,
			header,
			dataType: "json"
		});


		if (!!error) {
			let title = `网络错误，请检查你的网络是否稳定！`;
			uni.showToast({
				title: title,
				duration: 1500,
				mask: true,
				icon: 'none'
			});
			return;
		}

		const {
			statusCode
		} = res;
		console.log('http status code', statusCode);

		if (statusCode !== 200) {
			const title = '服务异常，请稍后重试！';
			uni.showToast({
				title: title,
				duration: 1500,
				mask: true,
				icon: 'none'
			});
			return;
		}

		// 200的情况认为都是对的返回值，具体的交给页面处理
		resolve(res); // 错误码的情况交给具体的业务场景处理吧，不然错误码不好统一处理

	})
}